package de.westranger.forex.code.script;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

public final class MQLFileWriter {
	private static char delimiter = ';';
	
	private static Map<String,Integer> handles = new TreeMap<String,Integer>();
	private static Map<Integer,BufferedWriter> streams = new TreeMap<Integer,BufferedWriter>();

	public static int FileOpen(String fName, int i, char c) {
		int handle;
		if(!handles.containsKey(fName)){
			handle = handles.size()+1;
			handles.put(fName, handle);
			try {
				streams.put(handle, new BufferedWriter(new FileWriter(fName,true)));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			handle = handles.get(fName);
		}

		return handle;
	}

	public static void FileClose(int handle) {
		final BufferedWriter bw = streams.get(handle);
		streams.remove(handle);
		try {
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		for(String name:handles.keySet()){
			if(handles.get(name) == handle){
				handles.remove(name);
				break;
			}
		}
	}

	public static void FileSeek(int handle, int i, int sEEK_END) {}

	public static void FileWrite(int handle, double ... values) {
		try {
			final BufferedWriter bw = streams.get(handle);
			final StringBuilder sb = new StringBuilder();
			
			for(double d:values){
				sb.append(d);
				sb.append(delimiter);
			}

			sb.deleteCharAt(sb.length()-1);
			
			bw.write(sb.toString().replaceAll("\\.", ","));
			bw.newLine();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void FileWrite(int handle,String ... values) {
		try {
			final BufferedWriter bw = streams.get(handle);
			final StringBuilder sb = new StringBuilder();
			
			for(String s:values){
				sb.append(s);
				sb.append(delimiter);
			}

			sb.deleteCharAt(sb.length()-1);
			
			bw.write(sb.toString().replaceAll("\\.", ","));
			bw.newLine();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void CloseAll(){
		for(int handle:streams.keySet()){
			try {
				streams.get(handle).close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			streams.remove(handle);
		}
		handles.clear();
	}

	public static void FileWrite(int handle, long time, boolean currentBuy, boolean currentSell,int signalType, double d) {
		FileWrite(handle,Long.toString(time), Boolean.toString(currentBuy), Boolean.toString(currentSell),Integer.toString(signalType),Double.toString(d));
	}
}
